Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
How to perform both a spread "operation" AND a callback function with useState in React

I am using functional components instead of class-based components. I have a state of hikes that is an array of objects and whenever I want to add a new hike to that array, I invoke the following line:

setCoors((coors=> [...coors, newCoor]))

But I also NEED to have the state callback function implemented. This is what Ive tried and it "sort of" works.

setCoors({coors:[...coors, newCoor]}, ()=>{console.log(coors)} )

But this is what I get back:

{
   coors:[
      0: {lat: 37.00, lng: -100.12},
      1: {lat: 88.00, lng: 76.12},
   ]
}

But i dont want my coor state to be an object...I need it to be an array like this:

{
   [
      0: {lat: 37.00, lng: -100.12},
      1: {lat: 88.00, lng: 76.12},
   ]
}

I can probably destructure the object to get what i want but I wanna know if there is an actual solution to this with setState. Does anyone have an idea of achieving this while also implementing a callback function? Thank you in advance

about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!